<template>
  <div class="drawer-container">
    <el-drawer v-model="drawer">
      <!-- 头部 -->
      <template #header>
        <p>{{ isUpdate ? '编辑' : '添加' }}用户</p>
      </template>
      <!-- 中间 -->
      <template #default>
        <el-form
          :model="userFormData"
          :rules="userFormRules"
          ref="formRef"
          label-width="80px"
        >
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请填写用户姓名"
              v-model="userFormData.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称">
            <el-input
              placeholder="请填写用户昵称"
              v-model="userFormData.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input
              placeholder="请填写密码"
              v-model="userFormData.password"
              type="password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <!-- 底部 -->
      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup name="Drawer">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { addUser, updateUser } from '@/api/acl/user'
import type { User } from '@/api/acl/types'
/* import { number } from 'echarts' */
const isUpdate = computed(() => !!userFormData.id)
const drawer = ref(false)
const formRef = ref<FormInstance>()

const userFormData = reactive({
  username: '',
  name: '',
  password: '',
  id: undefined,
})

const userFormRules = {
  username: [
    { required: true, message: '请填写用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
  ],
  password: [{ required: true, message: '请填写用户密码', trigger: 'blur' }],
}

const submit = () => {
  // 非空断言(typescript语法) 断言前面内容不为空（不是undefined或null）
  formRef.value!.validate(async (valid) => {
    if (valid) {
      // 表单校验通过
      if (isUpdate.value) {
        await updateUser({
          id: userFormData.id,
          username: userFormData.username,
          name: userFormData.name,
        })
      } else {
        await addUser(userFormData)
      }
      ElMessage.success(`${isUpdate.value ? '修改' : '添加'}用户成功`)
      close()
      emit('success')
    }
  })
}

/* 取消 */

const close = () => {
  drawer.value = false
}

// 打开
/*
  Vue2 和 Vue3 不一样的地方：
    Vue2 通过 ref 获取子组件实例对象，能够直接得到子组件实例对象所有内容
    Vue3 通过 ref 获取子组件实例对象，默认得不到任何内容，想要得到内容，需要子组件通过特殊语法进行暴露 expose
*/
const open = (row?: User.UserItem) => {
  if (row) {
    // 添加id
    userFormData.id = row.id
    // 清空数据
    userFormData.username = row.username
    userFormData.name = row.name
    userFormData.password = ''
  } else {
    userFormData.id = undefined
    userFormData.username = ''
    userFormData.name = ''
    userFormData.password = ''
  }
  formRef.value?.clearValidate()
  drawer.value = true
}

// 对外暴露内容（将来其他组件可以通过ref获取到组件实例对象，进而使用）
defineExpose({
  open,
})

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const emit = defineEmits(['success'])
</script>

<style scoped lang="scss">
.drawer-container :deep(.el-drawer__header) {
  padding: 0 20px;
  font-size: 16px;
}
</style>
